﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace com.tiyma.components
{
    public class DBManager
    {
    
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string i_str_sql, string i_connection_string)
        {
            using (SqlConnection connection = new SqlConnection(i_connection_string))
            {
                using (SqlCommand cmd = new SqlCommand(i_str_sql, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static int GetTableRowCount(string i_table_name, string i_connection_string)
        {
            string t_str_sql = string.Format("select count(*) totalCount from {0}", i_table_name);
            int t_total_count = 0;
            using (SqlConnection connection = new SqlConnection(i_connection_string))
            {
                SqlCommand cmd = new SqlCommand(t_str_sql, connection);
                connection.Open();
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (myReader.Read())
                {
                    if (!int.TryParse(myReader["totalCount"].ToString(), out t_total_count))
                        t_total_count = 0;
                }
            }
            return t_total_count;
        }
    }
}
